package com.frost.case4;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

public class WatchTest implements Watcher {

    private ZooKeeper zookeeper;
    private CountDownLatch connectedSignal = new CountDownLatch(1);
    private final String path = "/example/path";

    @Override
    public void process(WatchedEvent event) {
        // 判断事件类型和状态
        if (event.getState() == Event.KeeperState.SyncConnected) {
            // 如果是连接事件，则计数器减一
            if (event.getType() == Event.EventType.None) {
                connectedSignal.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged) {
                // 如果是节点数据变化事件，则获取新的数据
                try {
                    System.out.println("Node data changed: " + path);
                    byte[] data = zookeeper.getData(path, true, null);
                    System.out.println("New node data: " + new String(data));
                } catch (InterruptedException | KeeperException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    public void connect(String connectionString, int sessionTimeout) throws InterruptedException {
//        zookeeper = new ZooKeeper(connectionString, sessionTimeout, this);
//        // 等待连接成功
//        connectedSignal.await();
//    }
//
//    public static void main(String[] args) throws Exception {
//        ZooKeeperWatcherExample example = new ZooKeeperWatcherExample();
//        example.connect("localhost:2181", 3000);
//
//        // 初始化节点（如果不存在）
//        example.zookeeper.exists(example.path, true);
//
//        // 运行其他逻辑，例如等待节点值的变化
//        Thread.sleep(Long.MAX_VALUE);
//    }
}
